package co.yixiang.modules.order.rest;

import co.y.t.hyfPay.Config;
import co.y.t.hyfPay.Safe;
import co.y.t.wechatPay.PayUtil;
import co.y.t.wechatPay.WxPayConfig;
import co.yixiang.enums.PayTypeEnum;
import co.yixiang.modules.order.service.YxStoreOrderService;
import co.yixiang.modules.order.vo.YxStoreOrderQueryVo;
import co.yixiang.modules.user.domain.ShoppingPayform;
import co.yixiang.modules.user.domain.YxUserRecharge;
import co.yixiang.modules.user.service.ShoppingPayformService;
import co.yixiang.modules.user.service.YxUserRechargeService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class HyfNotifyController {
    private final YxStoreOrderService storeOrderService;
	private final ShoppingPayformService shoppingPayformService;
	/*private final co.yixiang.modules.commission.rest.CommissionMainController CommissionMainController;
	private final co.yixiang.modules.commission.rest.TDMQMessageController TDMQMessageController;*/
	private final YxUserRechargeService userRechargeService;
	/*private final TDMQMessageController tdmqMessage;*/
	@Autowired
	private ApplicationEventPublisher publisher;

    @GetMapping("/notifyHyf")
    public void hyf_notify(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
       this.hyf_notify4post(request,response);
    }

	@PostMapping("/notifyHyf")
	public void hyf_notify4post(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println("后台异步推送通知");
		//lo.error("回调开始");
		HttpSession session = request.getSession();

		//W03RechargeBillMgr mgr =  (W03RechargeBillMgr)SpringContextUtil.getBean("W03RechargeBillMgr");
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		System.out.println("notifyUrl："+ Config.notifyUrl);
		System.out.println("后台支付完成返回的信息："+sb);
		//将json字符串转换为json对象
		JSONObject json=JSONObject.parseObject(sb.toString());
		String respCode = json.getString("respCode");
		String merchOrderNo = json.getString("merchOrderNo");
		String respMsg = json.getString("respMsg");
		String hicardAmount = json.getString("amount");
		BigDecimal amount = new BigDecimal(hicardAmount);
		amount = amount.multiply(new BigDecimal("0.01")).setScale(2);
		String hicardOrderNo = json.getString("hicardOrderNo");
		String returnBackIdList = json.getString("reserved");
		TreeMap<String, String> params2 = new TreeMap<String, String> ();
		params2.put("amount", Long.toString(json.getLong("amount")));
		if(json.containsKey("buyerId") && !"".equals(json.getString("buyerId"))){
			params2.put("buyerId",json.getString("buyerId"));
		}
		if(json.containsKey("buyerLogonId") && !"".equals(json.getString("buyerLogonId"))){
			params2.put("buyerLogonId",json.getString("buyerLogonId"));
		}
		if(json.containsKey("channelOrderNo")&& !"".equals(json.getString("channelOrderNo")) ) {
			params2.put("channelOrderNo",json.getString("channelOrderNo"));
		}

		if(json.containsKey("createTime")&& !"".equals(json.getString("createTime")) ) {
			params2.put("createTime",json.getString("createTime"));
		}
		if(json.containsKey("hicardMerchNo")&& !"".equals(json.getString("hicardMerchNo")) ) {
			params2.put("hicardMerchNo",json.getString("hicardMerchNo"));
		}
		if(json.containsKey("hicardOrderNo")&& !"".equals(json.getString("hicardOrderNo")) ) {
			params2.put("hicardOrderNo",json.getString("hicardOrderNo"));
		}
		if(json.containsKey("isCredit") && !"".equals(json.getString("isCredit"))){
			params2.put("isCredit",json.getString("isCredit"));
		}
		if(json.containsKey("merchOrderNo") && !"".equals(json.getString("merchOrderNo"))){
			params2.put("merchOrderNo",json.getString("merchOrderNo"));
		}

		if(json.containsKey("payTime") && !"".equals(json.getString("payTime"))){
			params2.put("payTime",json.getString("payTime"));
		}

		if(json.containsKey("payType") && !"".equals(json.getString("payType"))){
			params2.put("payType",json.getString("payType"));
		}
		if(json.containsKey("remark") && !"".equals(json.getString("remark"))){
			params2.put("remark",json.getString("remark"));
		}
		if(json.containsKey("respCode") && !"".equals(json.getString("respCode"))){
			params2.put("respCode",json.getString("respCode"));
		}

		if(json.containsKey("respMsg") && !"".equals(json.getString("respMsg"))){
			params2.put("respMsg",json.getString("respMsg"));
		}

		if(json.containsKey("version") && !"".equals(json.getString("version"))){
			params2.put("version",json.getString("version"));
		}
		String myRSign = Safe.sign(params2);
		String rSign = json.getString("sign");
		if(!myRSign.equals(rSign)){
			System.out.println("签名异常，支付失败!");
			return;
		}
		if("00".equals(respCode)){ //支付成功

			String payno = merchOrderNo;
			String order_id = merchOrderNo.split("-")[1];
			System.out.println("order_id====================="+order_id+"111111111111");
			if("hyf1000".equals(order_id)) {
				try {
					String orderId = merchOrderNo.split("-")[0];
					YxUserRecharge userRecharge = userRechargeService.getOne(Wrappers.<YxUserRecharge>lambdaQuery()
							.eq(YxUserRecharge::getOrderId,orderId));
					String user_id = merchOrderNo.split("-")[2];
					if (userRecharge.getPaid() == 0) {
						System.out.println("NotifyServlet 支付成功,开始写入订单信息");
						userRechargeService.updateRecharge(userRecharge);
						ShoppingPayform pf = shoppingPayformService.getPayform4no(payno);
						pf.setPaystatus("已支付");
						shoppingPayformService.updateById(pf);

					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else {
				//YxStoreOrderQueryVo vo = null;
				try {
					System.out.println(merchOrderNo);
					//Long uid = LocalUser.getUser().getUid();
					YxStoreOrderQueryVo vo = storeOrderService.getOrderInfo(order_id, null);
					System.out.println("order=====================" + vo);
					System.out.println("getPaid=====================" + vo.getPaid());
					if (vo.getPaid() == 0) {
						System.out.println("NotifyServlet 支付成功,开始写入订单信息");
						storeOrderService.paySuccess(vo.getOrderId(), PayTypeEnum.HYFMINI.getValue());
						ShoppingPayform pf = shoppingPayformService.getPayform4no(payno);
						pf.setPaystatus("已支付");
						shoppingPayformService.updateById(pf);
						//CommissionMainController.checkOrderGoodsclass(vo.getId().toString());
						//TDMQMessageController.tdmqMessage(vo.getId().toString());
						//pf.setPaystatus("未支付");
						//pfmgr.update4paySuccess(pf.getId().toString());
						/*tdmqMessage.tdmqMessage(vo.getId().toString());*/
						/*TemplateBean templateBean = TemplateBean.builder()
								.orderId(vo.getOrderId())
								.price(vo.getPayPrice().toString())
								.uid(vo.getUid())
								.templateType(TemplateListenEnum.TYPE_1.getValue())
								.build();
						publisher.publishEvent(new TemplateEvent(this,templateBean));*/
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} else {
			log.error("支付失败");
			//支付失败
			System.out.println("支付失败："+respMsg);
			//查找充值订单，回填充值状态
				/*if(!("3".equals(vo.getBillState()) || "4".equals(vo.getBillState()))){
					System.out.println("后台之前没有设置支付状态，现在设置成为失败");
					vo.setBillState("3");
					//vo.setPayDate(DateTime.today());
					vo.setResultCode(respMsg);
					try {
						mgr.update(vo);
					} catch (GeneralException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}*/
		}

		//分析返回数据，解析出订单号

		//查找充值订单，回填充值状态
	}

	@GetMapping("/hyf_return")
	public void hyf_return(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String rhtml = "";
		String shtml = "<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml'><head>	<base href='http://www.icloudful.com:80/hicardpay/'>    <meta charset='utf-8'>    <meta name='renderer' content='webkit'>    <meta name='viewport' content='width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0'/>	<link type='text/css' rel='stylesheet' href='build/framework/css/qr.css' />	<title>支付结果</title>	<script src='http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js'></script>	<script></script>			</head><body><div class='header'><div class='top'><div class='logo'><img src='build/framework/images/logo_o.png' width='124' /></div></div></div><div class='content'><div class='ct'><div class='ct_nr'>  <div class='saoyisao'>     <h1></h1>        ";
		String ehtml = "</div></div></div></div></body></html>";

		// 读取请求内容
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		System.out.println("前台支付完成返回的信息："+sb);
		if("".equals(sb.toString().trim())){
			System.out.println("没有返回信息!");

			String mhtml = "<div class='fk'>充值完成</div> <div class='gs'>充值结果请查询充值记录</div>";
			rhtml = shtml + mhtml + ehtml;


			response.setContentType("text/html; charset=GBK");
			response.getWriter().write(rhtml);
			return;
		}
		//将json字符串转换为json对象
		JSONObject json=JSONObject.parseObject(sb.toString());

		String respCode = json.getString("respCode");
		String merchOrderNo = json.getString("merchOrderNo");
		String respMsg = json.getString("respMsg");
		String hicardAmount = json.getString("amount");
		BigDecimal amount = new BigDecimal(hicardAmount);
		amount = amount.multiply(new BigDecimal("0.01")).setScale(2);
		String hicardOrderNo = json.getString("hicardOrderNo");


		//认证签名

		if("00".equals(respCode)){ //支付成功
			System.out.print("支付成功");
			//查找充值订单，回填充值状态

			String mhtml = "<div class='fk'>支付结果:" + respMsg + "</div>     <div class='gs'>账户充值</div>     <div class='jg'>￥" + amount + "</div>     <div class='jyh'>订单号:" + merchOrderNo + "</div>     <input type='hidden' id='hicardOrderNo' value='" + hicardOrderNo + "'>";
			rhtml = shtml + mhtml + ehtml;
		} else {
			//支付失败
			System.out.print("支付失败："+respMsg);
			//查找充值订单，回填充值状态

			String mhtml = "<div class='fk'>支付结果:充值失败</div>    <div class='gs'>账户充值</div>     <div class='jg'>￥0.01</div>     <div class='jyh'>订单号:1492535039265</div>     <input type='hidden' id='hicardOrderNo' value='g680345184675827712'>  </div></div></div></div></body></html>";
			rhtml = shtml + mhtml + ehtml;
		}
		response.setContentType("text/html; charset=GBK");
		response.getWriter().write(rhtml);
	}

	@RequestMapping(value = "/hyfMiniNotify")
	@ResponseBody
	public void wxNotify(HttpServletRequest request,
						 HttpServletResponse response) throws Exception {

		BufferedReader br = new BufferedReader(new InputStreamReader(
				(ServletInputStream) request.getInputStream()));

		String line = null;

		StringBuilder sb = new StringBuilder();

		while ((line = br.readLine()) != null) {

			sb.append(line);

		}

		br.close();

		// sb为微信返回的xml

		String notityXml = sb.toString();

		String resXml = "";

		System.out.println("接收到的报文：" + notityXml);

		Map<String, String> map = PayUtil.doXMLParse(notityXml);

		String returnCode = (String) map.get("return_code");

		if ("SUCCESS".equals(returnCode)) {

			// 验证签名是否正确

			Map<String, String> validParams = PayUtil.paraFilter(map); // 回调验签时需要去除sign和空值参数

			String validStr = PayUtil.createLinkString(validParams);// 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串

			String sign = PayUtil.sign(validStr, WxPayConfig.key, "utf-8")
					.toUpperCase();// 拼装生成服务器端验证的签名

			// 根据微信官网的介绍，此处不仅对回调的参数进行验签，还需要对返回的金额与系统订单的金额进行比对等

			if (sign.equals(map.get("sign"))) {

				/** 此处添加自己的业务逻辑代码start **/

				/** 此处添加自己的业务逻辑代码end **/

				// 通知微信服务器已经支付成功

				resXml = "<xml>"
						+ "<return_code><![CDATA[SUCCESS]]></return_code>"

						+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

			}
			Map hdmap = new HashMap();
			// String s =map.get("mch_id");
			// String hdmap=
			// (String)servletContext.getAttribute(map.get("mch_id").toString());
			/*hdmap = (HashMap) servletContext.getAttribute(map.get("mch_id")
					.toString());*/
			System.out.println("map读取：" + hdmap + "=================="
					+ map.get("mch_id").toString());
			String billId = hdmap.get("rechargeBillId").toString();
			String payType = (String) hdmap.get("payType");
			System.out.println("回掉测试：" + payType);
			String fieldName ="";
			String userDefine1 ="";
			/*if (payType != null && payType.equals("batch")) {
				String returnBackIds = hdmap.get("returnBackIds").toString();
				String returnNos = hdmap.get("returnNos").toString();
				fieldName =returnBackIds;
				userDefine1 =returnNos;
				returnBackService.batchUpdateUserDefine4(returnBackIds);
				System.out.println("回掉测试：" + returnBackIds);
			}else if (payType != null && payType.equals("policy")) {

			}  else {
				String returnBackId = hdmap.get("returnBackId").toString();
				ReturnBack rb = returnBackService.queryById(returnBackId);
				userDefine1 = rb.getReturnNo();
				fieldName =returnBackId;
				rb.setUserDefine4("已支付");
				returnBackService.updateByPrimaryKeySelective(rb);
			}*/

			//servletContext.removeAttribute(map.get("mch_id").toString());
			/*Recharge vo = rechargeService.queryById(billId);
			if (!("3".equals(vo.getBillState()) || "4"
					.equals(vo.getBillState()))) {
				System.out.println("后台之前没有设置支付状态，现在设置成为成功");
				vo.setBillState("4");
				vo.setArrivalAmount(vo.getBillAmount());
				vo.setPayDate(new Date());
				vo.setResultCode(map.get("mch_id"));
				vo.setFieldName(fieldName);
				vo.setUserDefine1(userDefine1);
				rechargeService.updateByPrimaryKeySelective(vo);
			}
*/
		} else {

			resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"

					+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";

		}

		System.out.println(resXml);

		System.out.println("微信支付回调数据结束");

		BufferedOutputStream out = new BufferedOutputStream(

				response.getOutputStream());

		out.write(resXml.getBytes());

		out.flush();

		out.close();

	}

}
